<?php
namespace app\member\controller;
use app\common\controller\Frontend;
use app\common\model\MemberInfo;
use app\common\model\Province;
use app\common\model\City;
use app\common\library\Token;
use think\facade\Hook;
use think\facade\Cookie;
use think\facade\Session;
use think\Validate;
use think\Alisms;
use think\cache\driver\Redis;
use fast\Request;
use fast\Random;
use fast\Date;
use fast\Cols;

class Member extends Frontend{
    protected $model = null;
    protected $middleware = ['Auth',];
    protected $noNeedLogin = ['register','sendsms','getinfo','alteraddress','getuserinfo','login','xcxlogin','getUserFromXcx','changeMobile','registerxcx','ifregisterxcx','updateinfo','list','updateweixin','savesearch'];
    protected $noNeedRight = ['*'];
    public function initialize(){
        parent::initialize();        
        $this->model = model('MemberLogin');
        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($member){
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $member['itemid'], $expire);
            Cookie::set('token', $member['token'], $expire);
        });
        Hook::add('user_register_successed', function ($uid){
            //设置Token
            $token = Random::uuid();
            Token::set($token, $uid, config('token.expire'));
            Cookie::set('token', $token);
            Cookie::set('uid', $uid);
            //生成邀请码
            $inviteCode = createInviteCode($uid);
            model('MemberLogin')->where('itemid',$uid)->update(['invitecode'=>$inviteCode]);
        });
        // Hook::add('user_delete_successed', function ($user) use ($auth) {
        //     Cookie::delete('uid');
        //     Cookie::delete('token');
        // });
        // Hook::add('user_logout_successed', function ($user) use ($auth) {
        //     Cookie::delete('uid');
        //     Cookie::delete('token');
        // });
    }
    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if (Cookie::get('uid')) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('member/index'));
        }
        // if ($this->request->_logined)
        //     $this->success('你已经登录过了，无需再登录', $url);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return false;
            }
            $member = $this->model->get(['username' => $account]);
            if (!$member) {
                $this->error(__('Account is incorrect'));
                return false;
            }

            if ($member['status'] != 1) {
                $this->error(__('Account is locked'));
                return false;
            }
            
            if ($member['password'] != md5(md5($password).$member['salt'])) {
                $this->error(__('Password is incorrect'));
                return false;
            }
            $ip = $this->request->ip();
            $time = time();

            //判断连续登录和最大连续登录
            // if ($member['logintime'] < Date::unixtime('day'))
            // {
            //     $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
            //     $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
            // }

            $member->prevtime = $member['logintime'];
            //记录本次登录的IP和时间
            $member->loginip = $ip;
            $member->logintime = $time;
            $member->save();
            $member['token'] = Random::uuid();
            Token::set($member['token'], $member['itemid'], config('token.expire'));
            //登录成功的事件
            Hook::listen("user_login_successed", $member);
            $this->success(__('Logged in successful').$synchtml, $url ? $url : url('member/index'));
            /*
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }
                
            } else {
                $this->error($this->auth->getError());
            }
            */
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        $this->view->assign('member',$this->request->_member);
        return $this->view->fetch();
    }
    /**
     * 手机登录
     */
    public function loginm(){
        $url = $this->request->request('url', '', 'trim');
        if (Cookie::get('uid')) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'require|token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }
    /**
     * 注册会员（PC）
     */
    public function register()
    {
        $url = $this->request->request('url', '', 'trim');
        // if ($this->request->_logined){
        //     $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('/member/member/index'));
        // }
        if ($this->request->isPost()) {
            $username = $this->request->post('mobile');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                //'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                //'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                //'captcha'   => 'require|captcha',
                '__token__' => 'require|token',
            ];

            $msg = [
                //'username.require' => 'Username can not be empty',
                //'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                //'captcha.require'  => 'Captcha can not be empty',
                //'captcha.captcha'  => 'Captcha is incorrect',
                //'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            $checkcode = Session::get('checkcode');
            //print_r($checkcode);print_r($captcha);
            if($captcha != $checkcode||!$checkcode){
                $this->error('验证码不正确，请重新输入');
            }
            
            if (!$result) {
                //$this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            // 检测用户名或邮箱、手机号是否存在
            if ($username && $this->model->getByUsername($username))
            {
                $this->error('抱歉，用户名已经存在');
                return FALSE;
            }
            if ($email && $this->model->getByEmail($email))
            {
                $this->error('抱歉，邮箱已经存在');
                return FALSE;
            }
            if ($mobile && $this->model->getByMobile($mobile))
            {
                $this->error('抱歉，手机号已经存在');
                return FALSE;
            }
            $params = array();
            $params['username'] = $mobile;
            $params['salt'] = Random::alnum();
            $params['password'] = $password;
            $params['loginip'] = $this->request->ip();
            $params['logintime'] = time();
            $params['prevtime'] = time();
            $params['mobile'] = $mobile;
            $params['groupid'] = model('MemberGroup')->getDefault();//$this->request->post('inviteid');
            //标识邀请人
            if($this->request->post('inviteid')){
                $item = $this->model->getByInviteCode($this->request->post('inviteid'));
                $params['inviter'] = $item['itemid'];
            }
            $memberid = $this->model->register($params);
            if ($memberid) {
                //注册成功的事件
                Hook::listen("user_register_successed", $memberid);
                $this->success(__('Sign up successful'), $url ? $url : url('/member/member/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('inviteid',$this->request->get('inviteid'));
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        $this->view->assign('member',$this->request->_member);
        //print_r($this->request->_istouch);exit;
        if($this->request->_istouch){
            return $this->view->fetch('register');
        }else{
            return $this->view->fetch('registerpc');
        }
        
    }
    public function list(){
        if(!$this->request->_logined){
            $this->error($this->request->_errormessage, 'member/member/login');
        }
        $searcharr = array();
        echo '成功请求';exit;
        $ms = model('MemberSearch')->where('memberid',$this->request->post('memberid'))->find();
        if($ms){
            // $ms->gender = $this->request->post('likegender');
            // $ms->education = $this->request->post('education');
            // $ms->cityid = $this->request->post('cityid');
            // $agarry = explode(',',$this->request->post('age'));
            // $ms->minage = $agarry[0];
            // $ms->maxage = $agarry[1];
            // $ms->save();
            if($ms->education){
                $searcharr[] = ['education','eq',$ms->education];
            }
            
            if($ms->cityid){
                $searcharr[] = ['cityid','eq',$ms->cityid];
            }
            
            if($ms->gender){
                $searcharr[] = ['gender','eq',$ms->gender];
            }
            
            $searcharr[] = array('born','>',strtotime('-'.$ms->maxage.'years'));
            $searcharr[] = array('born','<',strtotime('-'.$ms->minage.'years'));
        }
        //print_r($searcharr);exit;
        $totalpage = 1;
        $page = $this->request->post('page');
        $limit = $this->request->post('pagesize')?$this->request->post('pagesize'):5;
        $total = model('MemberInfo')->where($searcharr)->count();
        if($limit>0){
              $totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
        }
        $offset = $limit*($page-1);
        
        if($offset<$total){
            
            $list = model('MemberInfo')->where($searcharr)->order('createtime', 'desc')->limit($offset, $limit)->select();
            //$list = $this->model->where($searcharr)->order('status desc,createtime', 'desc')->select();
            for ($i=0; $i < count($list); $i++) {
                $list[$i]['city'] = model('City')->getNameById($list[$i]['cityid']);
            }
            $returnarry = array();
            $returnarry['code'] = '1';
            $returnarry['msg'] = '获取活动成功';
            $returnarry['data'] = $list;
            $returnarry['url'] = '';
            $returnarry['wait'] = '';
            print_r(json_encode($returnarry));exit;
            //print_r(json_encode($list));exit;
        }else{
            $list = array();
            $returnarry = array();
            $returnarry['code'] = '1';
            $returnarry['msg'] = '获取活动成功';
            $returnarry['data'] = $list;
            $returnarry['url'] = '';
            $returnarry['wait'] = '';
            print_r(json_encode($returnarry));exit;
        }
    }
    /**
    * 小程序获取用户资料
    */
    public function getuserinfo(){
        $arr = config('weixin.');
        //print_r(Request::request_get('https://api.douban.com/v2/movie/coming_soon'));exit;
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $url .= '?appid='.$arr['appid'].'&secret='.$arr['appsecret'];
        $url .= '&js_code='.$this->request->post('code').'&grant_type=authorization_code';
        $rrr = Request::request_get($url);
        $minfo = model('MemberInfo');
        $data = array();$arr = array();
        $arr['nickname'] = '';
        $arr['avatar'] = '';
        $arr['memberid'] = '';
        $arr['mobile'] = '';
        $arr['openid'] = '';
        $arr['provinceid'] = 0;
        $arr['cityid'] = 0;
        $arr['bornprovince'] = 0;
        $arr['borncity'] = 0;
        $arr['gender'] = 1;
        $arr['config'] = config('self.');
        $r = json_decode($rrr,true);

        $m = $minfo->get(['openid'=>$r['openid']]);
        if($m){
            $arr['nickname'] = $m['nickname'];
            $arr['avatar'] = $m['avatar'];
            $arr['memberid'] = $m['memberid'];
            $arr['mobile'] = $m['mobile'];
            $arr['provinceid'] = $m['provinceid'];
            $arr['cityid'] = $m['cityid'];
            //$arr['bornprovince'] = $m['bornprovince'];
            //$arr['borncity'] = $m['borncity'];
            $arr['gender'] = $m['gender'];
            $memlogin = \app\common\model\MemberLogin::get($m['memberid']);
            $arr['status'] = $memlogin->status;
        }else{
            //如果openid不存在，增加一个用户，尚未绑定手机号的用户
            $data2 = array();
            $data['itemid'] = Random::uuid();
            model('MemberLogin')->data($data,true)->isUpdate(false)->save();
            $data2['memberid'] = $data['itemid'];
            $data2['openid'] = $r['openid'];
            $data2['itemid'] = Random::uuid();
            model('MemberInfo')->data($data2,true)->isUpdate(false)->save();
            $datac = array();
            $datac['memberid'] = $data['itemid'];
            $datac['itemid'] = Random::uuid();
            model('MemberAuth')->data($datac,true)->isUpdate(false)->save();
            /*
            $datad = array();
            $datad['memberid'] = $data['itemid'];
            $datad['itemid'] = Random::uuid();
            $datad['openid'] = $r['openid'];
            model('MemberSearch')->data($datad,true)->isUpdate(false)->save();
            */
            $arr['status'] = 0;
        }
        $arr['openid'] = $r['openid'];
        $redis = new Redis;
        $r2 = Random::numeric(8);
        $redis->set($r2,$r['session_key'].'|'.$r['openid']);
        $arr['loginsessionkey'] = $r2;
        //{"session_key":"nF470C8ZAaaVFT3zE4O+NQ==","expires_in":7200,"openid":"oCdkM0b86E8Rh7v_GNXONlB2UNCU"}
        $returnarry = array();
        $returnarry['code'] = '1';
        $returnarry['msg'] = '获取信息';
        $returnarry['data'] = $arr;
        $returnarry['url'] = '';
        $returnarry['wait'] = '';
        print_r(json_encode($returnarry));exit;
    }
    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            /*
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);

            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return FALSE;
            }
            */
            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    //$uc = new \addons\ucenter\library\client\Client();
                    //$synchtml = $uc->uc_user_synlogout();
                }
                $this->success('重置密码成功！' . $synchtml, url('memberlogin/login'));
            } else {
                $this->error($this->auth->getError());
            }
        }

        $this->view->assign('title', __('修改密码'));
        return $this->view->fetch();
    }
    //更新资料
    public function updateinfo(){
      $url = $this->request->request('url');
      if ($this->request->isPost()) {
        $post = $this->request->param();

        unset($post['province']);unset($post['city']);
        $arr = array();
        $redis = new Redis;
        $post['nickname'] = base64_encode($post['nickname']);
        if(isset($post['code'])){
            //如果修改手机号的话，首先查看验证码
            $mobile = $redis->get($post['mobile']);
            
            if($mobile==$post['code']){
                unset($post['educationname']);unset($post['age']);
                $this->model->where('itemid',$post['memberid'])->update(['mobile'=>$post['mobile'],'status'=>'1','username'=>base64_encode($post['username'])]);
                unset($post['username']);unset($post['code']);unset($post['imgurls']);
                model('MemberInfo')->where('memberid',$post['memberid'])->update($post);
                $arr['code'] = 1;
                $arr['message'] = '修改成功';
                $arr['data'] = array();
                print_r(json_encode($arr));exit;
            }else{
                $arr['code'] = 0;
                $arr['message'] = '请输入正确的验证码';
                $arr['data'] = array();
                print_r(json_encode($arr));exit;
            }
        }else{
            unset($post['mobile']);
            $this->model->where('itemid',$post['memberid'])->update(['status'=>'1','username'=>base64_encode($post['username'])]);
            unset($post['username']);unset($post['educationname']);unset($post['age']);
            unset($post['imgurls']);
            model('MemberInfo')->where('memberid',$post['memberid'])->update($post);
            $arr['code'] = 1;
            $arr['message'] = '修改成功';
            $arr['data'] = array();
            print_r(json_encode($arr));exit;
        }
        
      }else{
        return $this->view->fetch();
      }
    }
    //保存查询条件
    public function savesearch(){
        $arr = array();
        $ms = model('MemberSearch')->where('memberid',$this->request->post('memberid'))->find();
        $ms->memberid = $this->request->post('memberid');
        //$arr[''] = 
        $ms->gender = $this->request->post('likegender');
        $ms->education = $this->request->post('education');
        $ms->cityid = $this->request->post('cityid');
        
        $agarry = explode(',',$this->request->post('age'));
        $ms->minage = $agarry[0];
        $ms->maxage = $agarry[1];            
        $ms->save();
        
        $returnarry = array();
        $returnarry['code'] = '1';
        $returnarry['msg'] = '添加条件成功';
        $returnarry['data'] = array();
        $returnarry['url'] = '';
        $returnarry['wait'] = '';
        print_r(json_encode($returnarry));exit;
    }

    
    /**
     * 注册会员
     */
    public function reg(){
        $url = $this->request->request('url');
        if ($this->request->isPost()) {
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $checkcode = $this->request->post('checkcode');
            $redis = new Redis;
            $checkcode2 = $redis->get($mobile);
            if($checkcode != $checkcode2){
                $this->error('验证码不对，请重试');exit;
            }
            if ($this->auth->register($mobile, $password, $email, $mobile)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                     //$uc = new \addons\ucenter\library\client\Client();
                     //$synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                //print_r($this->auth->itemid);exit;
                Cookie::set('userid',$this->auth->itemid,30*86400);
                Cookie::set('username',$mobile,30 * 86400);
                $this->success(__('注册成功') . $synchtml, $url ? $url : url('member/index'));
            } else {
                $this->error($this->auth->getError());
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }
    //修改地址
    public function alteraddress(){
        $mobile = $this->request->post('mobile');
        $m = $this->model->get(['mobile'=>$mobile]);
        $arr = array();
        if($m){
            //$minfo = model('MemberInfo')->get(['memberid'=>$m['itemid']]);
            $address = $this->request->post('address');
            model('MemberInfo')->where('memberid',$m['itemid'])->update(['address'=>$address]);
            $arr['code'] = 1;
            $arr['message'] = '修改成功';
        }else{
            $arr['code'] = 0;
            $arr['message'] = '修改失败';
        }
        print_r(json_encode($arr));exit;
    }
    //把微信资料更新到会员资料里面。
    public function updateweixin(){
        if ($this->request->isPost()) {
            $post = array();
            $post['weixinhead'] = $this->request->post('weixinhead');
            $post['nickname'] = $this->request->post('nickname');
            $post['truename'] = $this->request->post('nickname');
            model('MemberInfo')->allowField(true)->save($post,['memberid' => $this->request->post('memberid')]);
            $arr = array();
            $arr['code'] = 1;
            $arr['message'] = '更新成功';
            $arr['data'] = array();
            print_r(json_encode($arr));exit;
        }
    }
      /**
      * 更换绑定的手机号
      * @param string $mobile 手机号
      * @param string $openid 登录的loginsessionkey
      */
      public function changeMobile(){
          $arr = array();$redis = new Redis;
          $mobile = $this->request->post('mobile');
          $openid = $this->request->post('openid');
          $me = $this->model->get(['mobile'=>$mobile]);
          if($me){
            $arr['code'] = -2;
            $arr['message'] = '手机号已经存在';
            print_r(json_encode($arr));exit;
          }
          //判断验证码是否正确
          $s = $redis->get($mobile);
          if(($s!='')&&($s == $this->request->post('checkcode'))){
            //增加一个用户,绑定openid返回手机号
            $r = $redis->get($openid);
            if($r){
              $rary = explode('|',$r);
              $oid = $rary[1];//openid
              $data = array();
              $this->model->where('username',$oid)->update(['mobile'=>$mobile]);
              model('MemberInfo')->where('openid',$oid)->update(['mobile' => $mobile]);
              $arr['code'] = 1;
              $arr['message'] = '绑定成功';
              //$arr['mobile'] =
            }else{
              $arr['code'] = -1;
              $arr['message'] = '登录超时';
            }
          }else{
            $arr['code'] = 0;
            $arr['message'] = '验证码不对，请重试';
          }
          print_r(json_encode($arr));exit;
      }
      /**
      * 通过会员编号得到会员信息
      * @param string $mobile 手机号
      */
      public function getinfo(){
          $memberid = $this->request->post('memberid');
          $m = $this->model->with('memberinfo')->where(['itemid'=>$memberid])->find();
          //$m['memberinfo']['gender'] = ($m['memberinfo']['gender']==1?'男':'女');
          $persondata = array();
          $persondata['avatar'] = $m['memberinfo']['avatar'];
          $persondata['picture1'] = $m['memberinfo']['picture1'];
          $persondata['picture2'] = $m['memberinfo']['picture2'];
          $persondata['gender'] = $m['memberinfo']['gender'];
          $persondata['truename'] = $m['memberinfo']['truename'];
          $persondata['mobile'] = $m['mobile'];
          $persondata['idno'] = $m['memberinfo']['idno'];
          $persondata['email'] = $m['memberinfo']['email'];
          $persondata['phone'] = $m['memberinfo']['phone'];
          $persondata['weixin'] = $m['memberinfo']['weixin'];
          $persondata['openid'] = $m['memberinfo']['openid'];
          $persondata['credit'] = $m['memberinfo']['credit'];
          $persondata['content'] = $m['memberinfo']['content'];
          $persondata['money'] = $m['memberinfo']['money'];
          $persondata['ordercount'] = count(model('Order')->getOrderByMember($memberid));
          $persondata['province'] = model('Province')->getNameById($m['memberinfo']['provinceid']);
          $persondata['provinceid'] = $m['memberinfo']['provinceid'];
          $persondata['city'] = model('City')->getNameById($m['memberinfo']['cityid']);
          $persondata['cityid'] = $m['memberinfo']['cityid'];
          $persondata['memberid'] = $m['itemid'];
          $persondata['username'] = $m['username'];
          $persondata['itemid'] = $m['itemid'];
          $imgurls = array();
          if($persondata['avatar']){
              $imgurls[] = $persondata['avatar'];
          }
          if($persondata['picture1']){
              $imgurls[] = $persondata['picture1'];
          }
          if($persondata['picture2']){
              $imgurls[] = $persondata['picture2'];
          }
          $persondata['imgurls'] = $imgurls;
          $arr = array();
          $arr['code'] = 1;
          $arr['message'] = '';
          $arr['data'] = $persondata;
          print_r(json_encode($arr));
          exit;
      }
    

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $synchtml = '';
        /*
        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS) {
            $uc = new \addons\ucenter\library\client\Client();
            $synchtml = $uc->uc_user_synlogout();
        }
        */
        $this->success(__('Logout successful') . $synchtml, url('member/index'));
    }
    
    public function ifregisterxcx(){
      if ($this->request->isPost()) {
          $mobile = $this->request->post('mobile', '');
          $meminfo = model('CompanyInfo')->get(['mobile'=>$mobile]);

          if($meminfo){
                $returnarry = array();
                $returnarry['code'] = 1;
                $returnarry['message'] = '抱歉，您已入驻，不能再次入驻';
                $returnarry['data'] = array();
                $returnarry['url'] = '';
                $returnarry['wait'] = 0;
                print_r(json_encode($returnarry));
                exit;
          }else{
                $returnarry = array();
                $returnarry['code'] = 0;
                $returnarry['message'] = '通过';
                $returnarry['data'] = array();
                $returnarry['url'] = '';
                $returnarry['wait'] = 0;
                print_r(json_encode($returnarry));
                exit;
          }
      }
    }
    /**
    * 小程序企业入驻
    */
    public function registerxcx(){
      if ($this->request->isPost()) {
          $password = $this->request->post('mobile', '');
          //$email = $this->request->post('email');
          $mobile = $this->request->post('mobile', '');
          //$captcha = $this->request->post('captcha');
          $checkcode = $this->request->post('checkcode');
          $openid = $this->request->post('openid', '');
          $redis = new Redis;
          $checkcode2 = $redis->get($mobile,'');

          if($checkcode != $checkcode2){
                $returnarry = array();
                $returnarry['code'] = 0;
                $returnarry['message'] = '验证码不对，请重试';
                $returnarry['data'] = array();
                $returnarry['url'] = '';
                $returnarry['wait'] = 0;
                print_r(json_encode($returnarry));
                exit;
          }

          $m = model('MemberLogin')->get(['username'=>$mobile]);
          //如果存在这个手机号，那么更新所有资料
          if($m){
              $arrin = array();
              $arrin['mobile'] = $mobile;
              model('MemberInfo')->where('memberid',$m['itemid'])->update($arrin);
              $arr = array();
              $arr['name'] = $this->request->post('name','');
              $arr['capital'] = $this->request->post('capital','');
              $arr['business'] = $this->request->post('business','');
              $arr['contact'] = $this->request->post('contact','');
              $arr['telephone'] = $this->request->post('telephone','');
              $arr['regyear'] = $this->request->post('regyear','');
              $arr['provinceid'] = $this->request->post('provinceid','0');
              $arr['cityid'] = $this->request->post('cityid','0');
              $arr['thumb'] = $this->request->post('thumb','');
              $arr['mobile'] = $mobile;
              //$arr['thumblicense'] = $this->request->post('thumblicense','');
              $ayt = $this->request->post("thumblicense/a");
              if(count($ayt)>0){
                  //$ayt = json_decode($this->request->post("thumblicense"),true);
                  $arr['thumblicense'] = implode(',',$ayt);
              }
              $arr['validated'] = 0;//重新验证
              model('CompanyInfo')->where('memberid',$m['itemid'])->update($arr);
              $returnarry = array();
              $returnarry['code'] = 1;
              $returnarry['message'] = '修改资料成功，请等待审核，在审核之前，您可以在会员中心发布现货或雕刻';
              $returnarry['data'] = array();
              $returnarry['url'] = '';
              $returnarry['wait'] = 0;
              print_r(json_encode($returnarry));exit;
          }else{
              $m = model('MemberInfo')->get(['openid'=>$openid]);
              $arrin = array();
              $arrin['mobile'] = $mobile;
              model('MemberInfo')->where('memberid',$m['memberid'])->update($arrin);
              $arry = array();
              $arry['loginip'] = $this->request->ip();
              $arry['password'] = md5(md5($password));
              $arry['payword'] = md5(md5($password));
              $arry['email'] = $mobile.'@163.com';
              $arry['mobile'] = $mobile;
              $arry['username'] = $mobile;
              model('MemberLogin')->where('itemid',$m['memberid'])->update($arry);
              $arr = array();
              $arr['name'] = $this->request->post('name','');
              $arr['capital'] = $this->request->post('capital','');
              $arr['business'] = $this->request->post('business','');
              $arr['contact'] = $this->request->post('contact','');
              $arr['telephone'] = $this->request->post('telephone','');
              $arr['regyear'] = $this->request->post('regyear','');
              $arr['provinceid'] = $this->request->post('provinceid','0');
              $arr['cityid'] = $this->request->post('cityid','0');
              $arr['thumb'] = $this->request->post('thumb','');
              $arr['mobile'] = $mobile;
              //$arr['thumblicense'] = $this->request->post('thumblicense','');
              $ayt = $this->request->post("thumblicense/a");
              if(count($ayt)>0){
                  //$ayt = json_decode($this->request->post("thumblicense"),true);
                  //print_r($ayt);exit;
                  $arr['thumblicense'] = implode(',',$ayt);
              }
              $arr['validated'] = 0;//重新验证
              model('CompanyInfo')->where('memberid',$m['memberid'])->update($arr);
              $returnarry = array();
              $returnarry['code'] = 1;
              $returnarry['message'] = '注册成功，请等待审核，在审核之前，您可以在会员中心发布现货或雕刻';
              $returnarry['data'] = array();
              $returnarry['url'] = '';
              $returnarry['wait'] = 0;
              print_r(json_encode($returnarry));exit;
          }
          //如果不存在手机号，更新所有会员资料
      }
    }
  /**
  * 发送短信
  * @param string $mobile 手机号
  * @param string $message 消息
  */
  public function sendsms(){
      $mobile = $this->request->post('mobile');
      $message = $this->request->post('message');
      $sec = $this->request->post('second',120);//60秒有效期
      $r2 = Random::numeric(4);
      // $aliarry = json_decode($this->self['alisms'],true);
      // $alisms = new Alisms($aliarry);
      // $result = $alisms->mobile($mobile)
      //         ->template($aliarry['checkcode'])
      //         ->param(['code' => $r2])
      //         ->send();
      //print_r($result);exit;
      send_sms($mobile, $message.$r2);
      $redis = new Redis;
      $redis->set($mobile,$r2,$sec);
      $arr = array();
      $arr['code'] = 1;
      $arr['message'] = '';
      print_r(json_encode($arr));exit;
  }
  /**
  * 小程序登录--换绑手机号
  * @param string $mobile   手机号
  * @param string $openid   OPENID
  * @param string $nickname 昵称
  * @param string $avatar   头像
  */
  public function xcxlogin(){
      $arr = array();$redis = new Redis;
      $mobile = $this->request->post('mobile');
      $openid = $this->request->post('openid');
      $nickname = $this->request->post('nickname');
      $avatar = $this->request->post('avatar');
      $me = $this->model->get(['mobile'=>$mobile]);
      if($me){
          $arr['code'] = -2;
          $arr['msg'] = '手机号已经存在';
          $arr['data'] = array();
          $arr['url'] = '';
          $arr['wait'] = 0;
          print_r(json_encode($arr));exit;
      }else{
          $s = $redis->get($mobile);
          if($s == $this->request->post('checkcode')){
              $openid = $this->request->post('openid');
              $minfo = model('MemberInfo')->get(['openid'=>$openid]);
              $uarry = array();
              $uarry['username'] = $mobile;
              $uarry['mobile'] = $mobile;
              $uarry['password'] = md5(md5($mobile));
              $uarry['payword'] = md5(md5($mobile));
              $uarry['email'] = $mobile.'@163.com';
              $this->model->where('itemid',$minfo['memberid'])->update($uarry);
              model('MemberInfo')->where('memberid',$minfo['memberid'])->update(['mobile' => $mobile]);
              $arr['code'] = 1;
              $arr['msg'] = '绑定成功';
              $arr['data'] = array(['mobile'=>$mobile]);
              $arr['url'] = '';
              $arr['wait'] = 0;
              print_r(json_encode($arr));exit;
          }else{
              $arr['code'] = 0;
              $arr['msg'] = '验证码不对，请重试';
              $arr['data'] = array();
              $arr['url'] = '';
              $arr['wait'] = 0;
              print_r(json_encode($arr));exit;
          }
      }
  }
  public function info(){
      print_r($this->self);
  }
    public function index(){
        $url = $this->request->request('url');
        if (!$this->request->_logined){
            $this->success(__('You are not logged in'), $url ? $url : url('/member/member/login'));
        }
        $this->view->assign('title', __('User center'));
        $this->view->assign('member',$this->request->_member);
        return $this->view->fetch();
    }
}
?>
